package org.jeecg.modules.demo.integrityArchive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.integrityArchive.entity.IntegrityArchive;
import org.jeecg.modules.demo.integrityArchive.mapper.IntegrityArchiveMapper;
import org.jeecg.modules.demo.integrityArchive.service.IIntegrityArchiveService;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 廉洁档案表
 * @Author: jeecg-boot
 * @Date:   2025-04-08
 * @Version: V1.0
 */
@Service
public class IntegrityArchiveServiceImpl extends ServiceImpl<IntegrityArchiveMapper, IntegrityArchive> implements IIntegrityArchiveService {



//    private static final ExecutorService executorService = Executors.newSingleThreadExecutor();
    @Override
    public String uploadSceneFile(IntegrityArchive integrityArchive) throws Exception {
        this.addIntegrityArchive(integrityArchive);
        return "添加成功";
    }




    @Override
    public List<SelectTreeModel> queryListByPid(String pid) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, null);
    }


    public List<SelectTreeModel> queryListByCode(String parentCode) {
        String pid = ROOT_PID_VALUE;
        if (oConvertUtils.isNotEmpty(parentCode)) {
            LambdaQueryWrapper<IntegrityArchive> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(IntegrityArchive::getPid, parentCode);
            List<IntegrityArchive> list = baseMapper.selectList(queryWrapper);
            if (list == null || list.size() == 0) {
                throw new JeecgBootException("该编码【" + parentCode + "】不存在，请核实!");
            }
            if (list.size() > 1) {
                throw new JeecgBootException("该编码【" + parentCode + "】存在多个，请核实!");
            }
            pid = list.get(0).getId();
        }
        return baseMapper.queryListByPid(pid, null);
    }


    @Override
    public void addIntegrityArchive(IntegrityArchive integrityArchive) {
        //新增时设置hasChild为0
        integrityArchive.setHasChild(IIntegrityArchiveService.NOCHILD);
        if(oConvertUtils.isEmpty(integrityArchive.getPid())){
            integrityArchive.setPid(IIntegrityArchiveService.ROOT_PID_VALUE);
        }else{
            //如果当前节点父ID不为空 则设置父节点的hasChildren 为1
            IntegrityArchive parent = baseMapper.selectById(integrityArchive.getPid());
            if(parent!=null && !"1".equals(parent.getHasChild())){
                parent.setHasChild("1");
                baseMapper.updateById(parent);
            }
        }
        baseMapper.insert(integrityArchive);
    }

    @Override
    public void updateIntegrityArchive(IntegrityArchive integrityArchive) {
        IntegrityArchive entity = this.getById(integrityArchive.getId());
        if(entity==null) {
            throw new JeecgBootException("未找到对应实体");
        }
        String old_pid = entity.getPid();
        String new_pid = integrityArchive.getPid();
        if(!old_pid.equals(new_pid)) {
            updateOldParentNode(old_pid);
            if(oConvertUtils.isEmpty(new_pid)){
                integrityArchive.setPid(IIntegrityArchiveService.ROOT_PID_VALUE);
            }
            if(!IIntegrityArchiveService.ROOT_PID_VALUE.equals(integrityArchive.getPid())) {
                baseMapper.updateTreeNodeStatus(integrityArchive.getPid(), IIntegrityArchiveService.HASCHILD);
            }
        }
        baseMapper.updateById(integrityArchive);
    }

    @Override
    public void removeIntegrityArchive(String id) {
        //查询选中节点下所有子节点一并删除
        id = this.queryTreeChildIds(id);
        if(id.indexOf(",")>0) {
            StringBuffer sb = new StringBuffer();
            String[] idArr = id.split(",");
            for (String idVal : idArr) {
                if(idVal != null){
                    IntegrityArchive integrityArchive = this.getById(idVal);
                    String pidVal = integrityArchive.getPid();
                    //查询此节点上一级是否还有其他子节点
                    List<IntegrityArchive> dataList = baseMapper.selectList(new QueryWrapper<IntegrityArchive>().eq("pid", pidVal).notIn("id", Arrays.asList(idArr)));
                    boolean flag = (dataList == null || dataList.size() == 0) && !Arrays.asList(idArr).contains(pidVal) && !sb.toString().contains(pidVal);
                    if(flag){
                        //如果当前节点原本有子节点 现在木有了，更新状态
                        sb.append(pidVal).append(",");
                    }
                }
            }
            //批量删除节点
            baseMapper.deleteBatchIds(Arrays.asList(idArr));
            //修改已无子节点的标识
            String[] pidArr = sb.toString().split(",");
            for(String pid : pidArr){
                this.updateOldParentNode(pid);
            }
        }else{
            IntegrityArchive integrityArchive = this.getById(id);
            if(integrityArchive==null) {
                throw new JeecgBootException("未找到对应实体");
            }
            updateOldParentNode(integrityArchive.getPid());
            baseMapper.deleteById(id);
        }
    }

    @Override
    public void removeAll(List<String> ids) {
        LambdaQueryWrapper<IntegrityArchive> queryWrapper = new LambdaQueryWrapper<>();
        baseMapper.delete(queryWrapper.in(IntegrityArchive::getPid, ids));
    }

    @Override
    public IntegrityArchive getByPid(String id) {
        return baseMapper.getByPid(id);
    }

    @Override
    public List<IntegrityArchive> queryByPid(String id) {
        return baseMapper.queryByPid(id);
    }

    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if(pidVal != null){
                if(!sb.toString().contains(pidVal)){
                    if(sb.toString().length() > 0){
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal,sb);
                }
            }
        }
        return sb.toString();
    }
    private StringBuffer getTreeChildIds(String pidVal,StringBuffer sb){
        List<IntegrityArchive> dataList = baseMapper.selectList(new QueryWrapper<IntegrityArchive>().eq("pid", pidVal));
        if(dataList != null && dataList.size()>0){
            for(IntegrityArchive tree : dataList) {
                if(!sb.toString().contains(tree.getId())){
                    sb.append(",").append(tree.getId());
                }
                this.getTreeChildIds(tree.getId(),sb);
            }
        }
        return sb;
    }
    private void updateOldParentNode(String pid) {
        if(!IIntegrityArchiveService.ROOT_PID_VALUE.equals(pid)) {
            Long count = baseMapper.selectCount(new QueryWrapper<IntegrityArchive>().eq("pid", pid));
            if(count==null || count<=1) {
                baseMapper.updateTreeNodeStatus(pid, IIntegrityArchiveService.NOCHILD);
            }
        }
    }


    //文件夹删除
    public static void deleteFolder(File folder) {
        // 验证是否为文件夹
        if (folder.isDirectory()) {
            // 获取文件夹中的所有文件和子文件夹
            File[] files = folder.listFiles();

            if (files != null) {
                // 递归删除文件夹中的所有文件和子文件夹
                for (File file : files) {
                    deleteFolder(file);
                }
            }
        }
        // 删除空文件夹
        boolean isDeleted = folder.delete();

        if (isDeleted) {
            System.out.println("Folder deleted: " + folder.getAbsolutePath());
        } else {
            System.out.println("Failed to delete folder: " + folder.getAbsolutePath());
        }
    }



}
